<template>
  <div class="home-overview">
    <!-- 用户信息 -->
    <div class="user-meta">
      <div class="avatar">
        <img :src="userStore.userInfo?.userInfo.avatar"/>
      </div>
      <h4>{{ userStore.userInfo?.userInfo.username }}</h4>
    </div>
    <div class="item">
      <!--      <a href="javascript:;">-->
      <!--        <span class="iconfont icon-hy"></span>-->
      <!--        <p>会员中心</p>-->
      <!--      </a>-->
      <a href="javascript:;" @click="openSettingModel">
        <span class="iconfont icon-aq"></span>
        <p>安全设置</p>
      </a>
      <a href="javascript:;" @click="openAddressModel">
        <span class="iconfont icon-dw"></span>
        <p>地址管理</p>
      </a>
    </div>
  </div>
  <div class="like-container">
    <div class="home-panel">
      <div class="header">
        <h4 data-v-bcb266e0="">猜你喜欢</h4>
      </div>
      <div class="goods-list">
        <GoodsItem v-for="good in likeList" :key="good.id" :good="good"/>
      </div>
    </div>
  </div>

  <!-- 地址管理模态框 -->
  <el-dialog v-model="showAddressModel" title="地址管理">
    <div v-for="address in addresses" :key="address.id" class="address-item"
         :class="{ 'active': activeAddress === address }" @mouseover="activeAddress = address"
         @mouseleave="activeAddress = null">
      <p>收货人：{{ address.receiver }}</p>
      <p>联系方式：{{ address.contact }}</p>
      <p>详细地址：{{ address.fullLocation }} {{ address.address }}</p>
      <div class="address-actions">
        <el-button @click="editAddress(address)" type="success" size="small">修改</el-button>
        <el-button @click="deleteAddress(address)" type="danger" size="small">删除</el-button>
        <el-button @click="setDefaultAddress(address)" type="primary" size="small" :disabled="address.isDefault == 0">
          设为默认地址
        </el-button>
      </div>
    </div>

    <!-- 编辑地址的弹窗 -->
    <el-dialog v-model="editDialogVisible" title="修改地址" destroy-on-close>
      <!-- 编辑地址的表单 -->
      <el-form :model="editAddressForm" ref="editForm" :rules="editAddressRules" label-width="80px">
        <el-form-item label="收货人" prop="receiver">
          <el-input v-model="editAddressForm.receiver"></el-input>
        </el-form-item>
        <el-form-item label="联系方式" prop="contact">
          <el-input v-model="editAddressForm.contact"></el-input>
        </el-form-item>
        <!-- 使用 el-cascader 来选择地区 -->
        <el-form-item prop="fullLocation" label="地区" required>
          <el-cascader
              v-model="editAddressForm.fullLocation"
              :options="pcaTextArr"
              placeholder="请选择地区"
              style="width: 100%"
          >
          </el-cascader>
        </el-form-item>
        <el-form-item prop="address" label="详细地址" required>
          <el-input v-model="editAddressForm.address" placeholder="请输入详细地址"></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" style="margin-right: 10px">
        <el-button size="small" @click="editDialogVisible = false">取消</el-button>
        <el-button size="small" type="primary" @click="saveEditedAddress">保存</el-button>
      </div>
    </el-dialog>
  </el-dialog>

  <el-dialog v-model="showSettingModel" title="安全设置" @close="clearSettingForm" :destroy-on-close="true">
    <el-form ref="settingRef" :model="settingForm" label-width="120px" :rules="settingFormRules">
      <el-form-item label="新密码" prop="newPassword">
        <el-input type="password" v-model="settingForm.newPassword"/>
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input type="password" v-model="settingForm.confirmPassword"/>
      </el-form-item>
    </el-form>
    <div style="margin-left: 460px">
      <el-button type="primary" @click="saveSettings">保存</el-button>
      <el-button @click="cancelSettings">取消</el-button>
    </div>
  </el-dialog>
</template>

<script setup>
import {useUserStore} from '@/stores/userStore';
import {getLikeListAPI, updatePassword} from '@/apis/user'
import {ref} from 'vue'
import {onMounted} from 'vue';
import GoodsItem from '@/views/Home/components/GoodsItem.vue'
import {deleteAddressAPI, getAddressesAPI, setDefaultAddressAPI, updateAddressAPI} from "@/apis/address";
import {pcaTextArr} from "element-china-area-data";
import router from "@/router";
import {ElMessage} from "element-plus";

const userStore = useUserStore()

const likeList = ref([])

const addresses = ref([]) // 添加地址列表的数据

// 获取地址列表
const getAddress = async () => {
  const {data} = await getAddressesAPI()
  addresses.value = data
}

const getLikeList = async () => {
  const res = await getLikeListAPI({limit: 4})
  likeList.value = res.data
}

// 控制地址管理模态框显示与隐藏的状态
const showAddressModel = ref(false);

const openAddressModel = () => {
  showAddressModel.value = true
}
const settingForm = ref({
  newPassword: '',
  confirmPassword: ''
});

const confirmPasswordValidator = (rule, value, callback) => {
  if (value !== settingForm.value.newPassword) {
    callback(new Error('两次输入密码不一致'));
  } else {
    callback();
  }
};

const settingFormRules = ref({
  newPassword: [
    {required: true, message: '新密码不能为空', trigger: 'blur'},
    {min: 5, message: '密码长度至少为5个字符', trigger: 'blur'},
  ],
  confirmPassword: [
    {required: true, message: '请再次输入密码', trigger: 'blur'},
    {validator: confirmPasswordValidator, trigger: 'blur'}
  ]
});

const showSettingModel = ref(false);

const settingClose = () => {
  // Reset form fields and validation status
  settingForm.value.newPassword = '';
  settingForm.value.confirmPassword = '';
};

const openSettingModel = () => {
  showSettingModel.value = true;
};

const settingRef = ref(null)
const saveSettings = async () => {
  settingRef.value.validate(async (valid) => {
    if (valid){
      const { data } = await updatePassword(settingForm.value.newPassword);
      showSettingModel.value = false
      // 清除token
      userStore.clearUserInfo()
      // 重定向
      await router.push('/login');
      ElMessage.success(data.msg + "请重新登录！")
    }
  })
}

const cancelSettings = () => {
  showSettingModel.value = false
  clearSettingForm()
}

const clearSettingForm = () => {
  // Reset form fields and validation status
  settingForm.value.newPassword = '';
  settingForm.value.confirmPassword = '';
};

// 删除地址
const deleteAddress = async (address) => {
  console.log(address.id)
  await deleteAddressAPI(address.id)
  await getAddress()
}

// 设为默认地址
const setDefaultAddress = async (address) => {
  console.log(address)
  await setDefaultAddressAPI(address.id)
  await getAddress()
}

// 当前激活的地址（鼠标悬停时）
const activeAddress = ref(null);

// 控制编辑地址弹窗的显示与隐藏
const editDialogVisible = ref(false);

// 当前编辑的地址信息
const editAddressForm = ref({});

// 编辑地址的表单验证规则
const editAddressRules = ref({
  receiver: [{required: true, message: '请输入收货人', trigger: 'blur'}],
  contact: [{required: true, message: '请输入联系方式', trigger: 'blur'}],
  fullLocation: [
    {required: true, message: '请选择地区', trigger: 'change'}
  ],
  address: [
    {required: true, message: '请输入详细地址', trigger: 'blur'}
  ]
});

// 点击修改按钮，打开编辑地址的弹窗并填充当前地址信息
const editAddress = async (address) => {
  console.log(address)
  editAddressForm.value = {
    id: address.id,
    receiver: address.receiver,
    contact: address.contact,
    fullLocation: address.fullLocation.split(" "),
    address: address.address,
  };
  editDialogVisible.value = true;
};

// 保存编辑后的地址信息
const editForm = ref(null);
const saveEditedAddress = async () => {
  editForm.value.validate(async (valid) => {
    if (valid) {
      // 调用保存地址信息的接口
      // await saveEditedAddressAPI(editAddressForm.value);
      // editAddressForm.value.fullLocation = editAddressForm.fullLocation.join(' ')
      console.log(editAddressForm.value.fullLocation.toString().replaceAll(",", " "))
      editAddressForm.value.fullLocation = editAddressForm.value.fullLocation.toString().replaceAll(",", " ")
      await updateAddressAPI(editAddressForm.value)
      await getAddress();
      editDialogVisible.value = false;
    }
  });
}

onMounted(() => {
  getLikeList()
  getAddress()
})

</script>

<style scoped lang="scss">
.home-overview {
  height: 132px;
  background: url('@/assets/images/user-info.jpg') no-repeat center / cover;
  display: flex;

  .user-meta {
    flex: 1;
    display: flex;
    align-items: center;

    .avatar {
      width: 85px;
      height: 85px;
      border-radius: 50%;
      overflow: hidden;
      margin-left: 60px;

      img {
        width: 100%;
        height: 100%;
      }
    }

    h4 {
      padding-left: 26px;
      font-size: 18px;
      font-weight: normal;
      color: white;
    }
  }

  .item {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-around;

    &:first-child {
      border-right: 1px solid #f4f4f4;
    }

    a {
      color: white;
      font-size: 16px;
      text-align: center;

      .iconfont {
        font-size: 32px;
      }

      p {
        line-height: 32px;
      }
    }
  }
}

.like-container {
  margin-top: 20px;
  border-radius: 4px;
  background-color: #fff;
}

.home-panel {
  background-color: #fff;
  padding: 0 20px;
  margin-top: 20px;
  height: 400px;

  .header {
    height: 66px;
    border-bottom: 1px solid #f5f5f5;
    padding: 18px 0;
    display: flex;
    justify-content: space-between;
    align-items: baseline;

    h4 {
      font-size: 22px;
      font-weight: 400;
    }

  }

  .goods-list {
    display: flex;
    justify-content: space-around;
  }
}

.address-item {
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid #ccc;
  cursor: pointer;

  &:hover {
    background-color: #f5f5f5;
  }

  .address-actions {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    margin-top: 5px;

    button {
      margin-left: 5px;
    }
  }
}

.active {
  background-color: #f5f5f5;
}
</style>
